package forkjoin;

import java.util.Enumeration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

/**
 * @author lyx
 * @Date 2021/6/26 13:33
 */
public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test();//sum=499999999500000000  正常计算-时间为=6144
        //test1();//sum=499999999500000000  forkjoin-时间为=5963
       //test2();//sum=500000000500000000  Stream-时间为=149
    }

    //正常計算 非常慢
    public static void test()  {
        Long stime = System.currentTimeMillis();
        Long sum=0L;
        for (Long i = 0L; i < 10_0000_0000L; i++) {
            sum += i;
        }
        Long etime = System.currentTimeMillis();
        System.out.println("sum="+sum+"  正常计算-时间为="+(etime-stime));
    }


    //Forkjoin 速度中
    public static void test1() throws ExecutionException, InterruptedException {
        Long stime = System.currentTimeMillis();//开始时间

        ForkJoinPool forkJoinPool = new ForkJoinPool(); //forkjoin池
        ForkJoinTest forkJoinTest = new ForkJoinTest(0L,10_0000_0000L); //调用方法
        Long sum =  forkJoinPool.submit(forkJoinTest).get();//通提交方法,获取结果

        Long etime = System.currentTimeMillis();//结束时间
        System.out.println("sum="+sum+"    forkjoin-时间为="+(etime-stime));
    }


    //Stream流 速度快
    public static void test2(){
        Long start = System.currentTimeMillis();//开始事件
        //rangeClosed ()
        // range  (] 不包左
        Long sum = LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        Long end = System.currentTimeMillis();//结束时间

        System.out.println("sum="+sum+"  时间为="+(end-start));
    }

}
